package com.gx.smart.building.ui.inspection.fragment

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.navigation.fragment.findNavController
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.gx.smart.building.R
import com.gx.smart.building.databinding.FragmentInspectionSubmitBinding
import com.gx.smart.building.ui.common.adapter.ImageAdapter
import com.gx.smart.building.ui.common.fragment.UploadImageFragment
import com.gx.smart.building.ui.common.model.AttachmentInfo
import com.gx.smart.building.ui.inspection.adapter.InspectionResultAdapter
import com.gx.smart.building.ui.inspection.viewmodel.InspectionViewModel
import com.gx.smart.building.ui.photo.activity.CustomActivity
import com.gx.smart.building.ui.photo.fragment.PhotoPreviewFragment
import com.gx.smart.building.ui.photo.model.ImageViewInfo
import com.gx.smart.lib_http.BuildConfig
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.dto.PlanTaskAssetDto
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.dto.PlanTaskAssetFileDto
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.dto.PlanTaskAssetItemResultDto
import com.previewlibrary.GPreviewBuilder

class InspectionSubmitFragment : UploadImageFragment<InspectionViewModel>() {
    private lateinit var viewBinding: FragmentInspectionSubmitBinding
    private lateinit var resultAdapter: InspectionResultAdapter
//    private lateinit var planTaskAssetDto: PlanTaskAssetDto.Builder
    private var planTaskAssetFileDto: MutableList<PlanTaskAssetFileDto.Builder> = mutableListOf()
    private var planTaskAssetItemResultDto: MutableList<PlanTaskAssetItemResultDto.Builder> =
        mutableListOf()
    private val photoLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        val resultCode: Int = result.resultCode
        if (resultCode == Activity.RESULT_OK) {
            val uri: Uri? = result.data?.data
            val position = resultAdapter.selectedPosition
            val uploadImageUtil = resultAdapter.uploadImageUtil[position]
            if (uploadImageUtil.listener != null) {
                uploadImageUtil.listener.displayImage1(uri)
            }
            uploadImageUtil.UploadImageAsyncTask1().execute(uri)
        }
    }

    private val cameraLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            val resultCode: Int = result.resultCode
            if (resultCode == Activity.RESULT_OK) {
                val position = resultAdapter.selectedPosition
                val uploadImageUtil = resultAdapter.uploadImageUtil[position]
                if (uploadImageUtil.cameraUri != null) {
                    if (uploadImageUtil.listener != null) {
                        uploadImageUtil.listener.displayImage1(uploadImageUtil.cameraUri)
                    }
                    uploadImageUtil.UploadImageAsyncTask1().execute(uploadImageUtil.cameraUri)
                }
            }
        }


    /**
     * 同步图片信息
     */
    private fun setImages() {
        //去除删除的图片
        picList1.filter {
            attachmentAdapter1.dataList.map { item -> item.fileName }.contains(it.fileName)
        }
            .forEach { item ->
                planTaskAssetFileDto.add(
                    PlanTaskAssetFileDto.newBuilder()
                        .setFileName(item.fileName)
                        .setFileUrl(item.path)
                        .setFileType(1)
                )
            }
    }

    override fun uploadTask1(fileName: String, file: ByteArray) {
        viewModel.uploadImage(fileName, file)
    }

    override fun onBindLayout(): Int = R.layout.fragment_inspection_submit

    override fun getToolbarTitle(): String = "任务详情"

    override fun onBindViewModel(): Class<InspectionViewModel> = InspectionViewModel::class.java

    override fun initContentView(root: ViewGroup) {
        viewBinding = FragmentInspectionSubmitBinding.inflate(layoutInflater, root, true)
    }

    override fun initContent() {
        super.initContent()
        viewBinding.save.setOnClickListener {
            submit()
        }
        viewBinding.resultStatus.setOnCheckedChangeListener { _, isChecked ->
            //巡检/保养状态：1-正常，2-异常
//            planTaskAssetDto.resultStatus = if (isChecked) 2 else 1
        }
        viewBinding.resultDesc.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable) {
                viewBinding.wordCount.text = s.length.toString() + "/200"
            }
        })

    }

    override fun onStart() {
        super.onStart()
        val activity = requireActivity()
        KeyboardUtils.registerSoftInputChangedListener(activity) {
            if (KeyboardUtils.isSoftInputVisible(activity)) {
                viewBinding.submitLayout.visibility = View.GONE
            } else {
                viewBinding.submitLayout.visibility = View.VISIBLE
            }
        }
    }

    override fun initData() {
        viewModel.queryPlanTaskAssetDetail(
            requireArguments().getString("planTaskId")!!,
            requireArguments().getString("assetId")!!
        )
        viewModel.detail.observe(viewLifecycleOwner) {
//            planTaskAssetDto = PlanTaskAssetDto.newBuilder(it)

            viewBinding.assetCode.text = it.assetCode
            viewBinding.assetName.text = it.assetName
            viewBinding.assetTypeName.text = it.assetTypeName
            viewBinding.brandName.text = it.brandName
            viewBinding.modelName.text = it.modelName
            viewBinding.areaName.text = it.areaName
            handleStatus(it.handleStatus)


            viewBinding.resultDesc.apply {
                text = Editable.Factory.getInstance().newEditable(it.resultDesc)
            }
            //状态：1-已处理，2-未处理
            if (it.handleStatus == 1) {
                viewBinding.finishTimeLayout.visibility = View.VISIBLE
                viewBinding.finishTime.text =
                    TimeUtils.millis2String(it.handleTime, "yyyy-MM-dd HH:mm:ss")
                //巡检/保养状态：1-正常，2-异常
                viewBinding.resultStatus.isChecked = (it.resultStatus == 2)
            } else {
                viewBinding.finishTimeLayout.visibility = View.GONE
                //巡检/保养状态：1-正常，2-异常
//                planTaskAssetDto.resultStatus = 1
            }
        }
        planTaskAssetItemResultDto.clear()
        viewModel.detailResultList.observe(viewLifecycleOwner) { it ->
            planTaskAssetItemResultDto.addAll(it.map { result ->
                PlanTaskAssetItemResultDto.newBuilder(result).setResultValue("1")
            })
            resultAdapter.refresh(it)
        }
        viewModel.uploadSuccess.observe(viewLifecycleOwner) {

            val uploadSuccess: Boolean = it.isSuccess
            val fileName: String = it.fileName
            if (uploadSuccess) {
                picList1.add(it)
            } else {
                displayFailImage1(fileName)
            }
        }
        viewModel.adapterUploadSuccess.observe(viewLifecycleOwner) {
            val uploadSuccess: Boolean = it.isSuccess
            if (uploadSuccess) {
                val position = resultAdapter.selectedPosition
                planTaskAssetItemResultDto[position].addTaskAssetItemFileDto(
                    PlanTaskAssetFileDto.newBuilder()
                        .setFileName(it.fileName)
                        .setFileUrl(it.path)
                        .setFileType(1)
                        .build()
                )
            } else {
                val position = resultAdapter.selectedPosition
                val uploadImageUtil = resultAdapter.uploadImageUtil[position]
                if (uploadImageUtil.listener != null) {
                    uploadImageUtil.listener.displayFail()
                }
            }
        }
    }

    //状态：1-已处理，2-未处理
    private fun handleStatus(handleStatus: Int) {
        if (handleStatus == 1) {
            viewBinding.resultStatus.isEnabled = false
            viewBinding.resultDesc.isEnabled = false
            viewBinding.submitLayout.visibility = View.GONE
            imageAdapter()
        } else {
            viewBinding.resultStatus.isEnabled = true
            viewBinding.resultDesc.isEnabled = true
            viewBinding.submitLayout.visibility = View.VISIBLE
            attachmentAdapter()
        }
        resultAdapter =
            InspectionResultAdapter(
                requireActivity(), handleStatus, photoLauncher, cameraLauncher,
                viewModel, planTaskAssetItemResultDto
            )
        viewBinding.resultRecyclerView.adapter = resultAdapter
        viewModel.detailResultList.observe(viewLifecycleOwner) { it ->
            planTaskAssetItemResultDto.clear()
            planTaskAssetItemResultDto.addAll(it.map { result ->
                PlanTaskAssetItemResultDto.newBuilder(result)
            })
            resultAdapter.refresh(it)
        }
    }

    private fun imageAdapter() {
        viewBinding.attachmentRecyclerView.visibility = View.GONE
        viewBinding.imageRecyclerView.visibility = View.VISIBLE
        val imageAdapter = ImageAdapter(requireContext())
        viewBinding.imageRecyclerView.adapter = imageAdapter
        val imageViewInfoList: MutableList<ImageViewInfo> = mutableListOf()
        imageAdapter.setItemClickListener { _, position ->
            run {
                val bundle = Bundle()
                bundle.putSerializable("className", PhotoPreviewFragment::class.java)
                GPreviewBuilder.from(requireActivity())
                    .to(CustomActivity::class.java, bundle)
                    .setData(imageViewInfoList)
                    .setIsScale(true)
                    .setCurrentIndex(position)
                    .setSingleFling(true) //是否在黑屏区域点击返回
                    .setDrag(true) //是否禁用图片拖拽返回
                    .setType(GPreviewBuilder.IndicatorType.Number) //指示器类型
                    .start()
            }
        }
        viewModel.detailFileList.observe(viewLifecycleOwner) { it ->
            planTaskAssetFileDto.addAll(it.map { file ->
                PlanTaskAssetFileDto.newBuilder(file)
            })
            imageViewInfoList.clear()
            imageViewInfoList.addAll(
                it.map { workOrderFile ->
                    ImageViewInfo(BuildConfig.FILE_UPLOAD_URL + workOrderFile.fileUrl)
                }
            )

            imageAdapter.addAll(it.map {
                BuildConfig.FILE_UPLOAD_URL + it.fileUrl
            })
        }
    }

    private fun attachmentAdapter() {
        initAdapter1()
        viewBinding.attachmentRecyclerView.adapter = attachmentAdapter1
        viewModel.detailFileList.observe(viewLifecycleOwner) { it ->
            planTaskAssetFileDto.addAll(it.map { file ->
                PlanTaskAssetFileDto.newBuilder(file)
            })
            attachmentAdapter1.addAllFirst(it.map {
                AttachmentInfo(
                    3,
                    Uri.parse(""),
                    "",
                    false,
                    it.fileUrl
                )
            })
        }
    }

    private fun submit() {
//        planTaskAssetDto.resultDesc = viewBinding.resultDesc.text.toString().trim()
        if (!uploadImageAttachment1()) {
            return
        }
        setImages()

        if (planTaskAssetItemResultDto.count { it.imageRequire == 1 } >
            planTaskAssetItemResultDto.count { it.taskAssetItemFileDtoCount > 0 }
        ) {
            ToastUtils.showLong("工作流程项目中还有图片没有上传！")
            return
        }


//        viewModel.handleTask(
//            planTaskAssetDto.build(),
//            planTaskAssetFileDto.map { it.build() },
//            planTaskAssetItemResultDto.map { it.build() }
//        )
//            .observe(viewLifecycleOwner) {
//                if (it) {
                    val assetId = requireArguments().getString("assetId")
                    val assetName = requireArguments().getString("assetName")
                    val planTaskAssetId = requireArguments().getString("planTaskAssetId")
                    findNavController().navigate(
                        R.id.action_inspectionSubmitFragment_to_inspectionSubmitResultFragment,
                        Bundle().apply {
                            putString("assetId", assetId)
                            putString("assetName", assetName)
                            putString("planTaskAssetId", planTaskAssetId)
                        })
//                }
//            }
    }
}